package com.fanghuaiming.seata.order.tcc.idempotent;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: 第二阶段（confirm/cancel阶段）处理幂等性问题
 *               第二阶段 Confirm 或 Cancel 阶段对第一阶段的成功与否进行判断,在第一阶段成功时需要保存一个标识
 * @param:
 * @return:
 * @auther: fanghuaiming
 * @date: 2020/11/30 下午4:46
 * @version:1.0.0
 */
public class SeataTccOrderResultHolder {

    /**
     * 定义全局map保存
     */
    private static Map<Class<?>, Map<String, String>> map = new ConcurrentHashMap<Class<?>, Map<String, String>>();


    /**
     * @Description: 根据唯一事务xid设置阶段结果
     *
     * @param:
     * @return:
     * @auther: fanghuaiming
     * @date: 2020/11/30 下午4:45
     * @version:1.0.0
     */
    public static void setResult(Class<?> clazz, String xid, String value) {
        Map<String, String> results = map.get(clazz);

        if (results == null) {
            synchronized (map) {
                if (results == null) {
                    results = new ConcurrentHashMap<>();
                    map.put(clazz, results);
                }
            }
        }
        results.put(xid, value);
    }

    /**
     * @Description: 获取阶段结果
     *
     * @param:
     * @return:
     * @auther: fanghuaiming
     * @date: 2020/11/30 下午4:47
     * @version:1.0.0
     */
    public static String getResult(Class<?> clazz, String xid) {
        Map<String, String> results = map.get(clazz);
        if (results != null) {
            return results.get(xid);
        }
        return null;
    }

    /**
     * @Description: commit或delete后删除阶段结果
     *
     * @param:
     * @return:
     * @auther: fanghuaiming
     * @date: 2020/11/30 下午4:48
     * @version:1.0.0
     */
    public static void removeResult(Class<?> clazz, String xid) {
        Map<String, String> results = map.get(clazz);
        if (results != null) {
            results.remove(xid);
        }
    }
}
